package cn.jdy.plugins.websocket;

import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

/**
 * @desc   Socket建立连接（握手）和断开
 * @author ningqian
 * @date   2017-3-23
 *
 */
public class HandShake implements HandshakeInterceptor {

	@Override
	public boolean beforeHandshake(ServerHttpRequest request,ServerHttpResponse response, WebSocketHandler wsHandler,
			Map<String, Object> attributes) throws Exception {
			System.out.println("Websocket:用户[ID:" + ((ServletServerHttpRequest) request).getServletRequest().getSession(false).getAttribute("uid") + "]已经建立连接");
	        if (request instanceof ServletServerHttpRequest) {
	            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
	            HttpSession session = servletRequest.getServletRequest().getSession(false);
	            
	            if (session != null) {
	                //使用userName区分WebSocketHandler，以便定向发送消息
	            	Map<String, Object> watchUser = (Map<String, Object>) session.getAttribute("watchUser");
	            	attributes.put(Constants.WEBSOCKET_LIVEID,watchUser.get("liveId").toString());     //直播间id
	                attributes.put(Constants.WEBSOCKET_USERId,watchUser.get("openid").toString());     //用户唯一id
	                attributes.put(Constants.WEBSOCKET_USERNAME,watchUser.get("nickname").toString()); //用户昵称
	                attributes.put(Constants.WEBSOCKET_USERHEADIMG,watchUser.get("headimgurl").toString()); //头像
	                attributes.put(Constants.WEBSOCKET_USERSEX,watchUser.get("sex").toString());       //性别
	            }else{
	                return false;
	            }
	        }
	        return true;
	}

	@Override
	public void afterHandshake(ServerHttpRequest request,
			ServerHttpResponse response, WebSocketHandler wsHandler,
			Exception exception) {
		// TODO Auto-generated method stub
		
	}


}